<template>
  <!-- 查询区域 -->
  <div class="table-page-search-wrapper">
    <a-form layout="inline" @keyup.enter.native="searchQuery">
      <a-row :gutter="24">
        <a-col :md="6" :sm="8">
          <a-form-item label="被评估人姓名" :labelCol="{span: 5}" :wrapperCol="{span: 18, offset: 0}">
            <a-input placeholder="请输入" v-model="queryParam.assessedName" allowClear></a-input>
          </a-form-item>
        </a-col>
        <a-col :md="6" :sm="8">
          <a-form-item label="被评估人部门" :labelCol="{span: 5}" :wrapperCol="{span: 18, offset: 0}">
            <a-input placeholder="请输入" v-model="queryParam.assessedDept" allowClear></a-input>
          </a-form-item>
        </a-col>

        <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
          <a-col :md="4" :sm="24">
            <a-button type="primary" @click="searchQuery">查询</a-button>
            <a-button style="margin-left: 8px" @click="searchReset">重置</a-button>
          </a-col>
        </span>
      </a-row>
    </a-form>

    <!-- 操作按钮区域 -->
    <div class="table-operator" style="margin-top: 5px">
      <a-button type="primary" icon="download" @click="handleExportXls">导出总表</a-button>
      <a-button type="primary" icon="download" @click="handleExportDetailXls">导出个人明细</a-button>
    </div>

<!--    <h3>-->
<!--      直接上级{{ weight.directSuperior }}%，-->
<!--      相关上级{{ weight.relevantSuperiors }}%，-->
<!--      直接平级{{ weight.directSibling }}%，-->
<!--      相关平级{{ weight.relevantSibling }}%，-->
<!--      下级{{ weight.subordinate }}%，-->
<!--      权重进行加权-->
<!--      <a-popover title="权重列表">-->
<!--        <template slot="content">-->
<!--          <a-table rowKey="id" bordered :columns="columns2" :dataSource="weightList" :pagination="false"/>-->
<!--        </template>-->
<!--        <a-icon type="exclamation-circle" style="color: #999" />-->
<!--      </a-popover>-->
<!--    </h3>-->

    <a-table
        v-if="!visible"
        ref="table"
        size="middle"
        bordered
        :rowKey="(record, index) => index"
        :columns="columns"
        :dataSource="dataList"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange, type: 'radio'}"
        @change="tableChangeHandle">

        <span slot="action" slot-scope="text, record">
<!--          <a @click="handleDetail(record.id)">详情</a>-->
          <router-link :to="{ name: 'questionnaire-analyse-details', query: { questionId: queryParam.questionId, assessedId: record.assessedId } }">详情</router-link>
        </span>


    </a-table>

<!--    <a-tabs v-else>-->
<!--      <a-tab-pane key="1" tab="统计">-->
<!--        <a-table-->
<!--            ref="tongji"-->
<!--            size="middle"-->
<!--            bordered-->
<!--            rowKey="id"-->
<!--            :columns="tongji.columns"-->
<!--            :dataSource="tongji.dataList"-->
<!--            :pagination="false">-->
<!--        </a-table>-->
<!--        <div style="text-align: right;">-->
<!--          <b>总分：<span style="font-size: 24px; color: #2A82E4">{{ tongjiSum }}</span></b>-->
<!--        </div>-->
<!--      </a-tab-pane>-->
<!--      <a-tab-pane key="2" tab="明细">-->
<!--        <a-table-->
<!--            ref="mingxi"-->
<!--            size="middle"-->
<!--            bordered-->
<!--            rowKey="id"-->
<!--            :columns="mingxi.columns"-->
<!--            :dataSource="mingxi.dataList"-->
<!--            :pagination="false">-->
<!--        </a-table>-->
<!--      </a-tab-pane>-->
<!--      <a-icon type="close" slot="tabBarExtraContent" @click="onClose" />-->
<!--    </a-tabs>-->

  </div>
</template>

<script>

import { getAction, postAction } from '@/api/manage'
import qs from 'qs'
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'

export default {
  name: "analyse",
  data () {
    return {
      visible: false,
      loading: false,
      detailVisible: false,
      queryParam: {
        page: 1,
        limit: 10,
        questionId: '',
        assessedName: '',
        assessedDept: '',
      },
      weight: {
        directSuperior: '',
        relevantSuperiors: '',
        directSibling: '',
        relevantSibling: '',
        subordinate: '',
      },
      weightList: [],
      dataList: [
        // { username: '王欢', dept: '财务部', number: '45/60', sum: '72.00' },
        // { username: '王欢', dept: '财务部', number: '45/60', sum: '72.00' }
      ],
      selectedRowKeys: [],
      selectionRows: [],
      // tongjiSum: '72.00',
      // tongji: {
      //   dataList: [
      //     { id: '1', relations: '直接上级', title1: '题目1', title2: '题目2', title3: '题目3', title4: '题目4' },
      //     { id: '2', relations: '相关上级', title1: '题目1', title2: '题目2', title3: '题目3', title4: '题目4' },
      //   ],
      //   columns: [
      //     {
      //       title: '评估人与被评估人关系',
      //       dataIndex: 'relations',
      //       align: "center",
      //       width: 180
      //     },
      //     {
      //       title: '题目1',
      //       dataIndex: 'title1',
      //       align: "center",
      //     },
      //     {
      //       title: '题目2',
      //       dataIndex: 'title2',
      //       align: "center",
      //     },
      //     {
      //       title: '题目3',
      //       dataIndex: 'title3',
      //       align: "center",
      //     },
      //     {
      //       title: '题目4',
      //       dataIndex: 'title4',
      //       align: "center",
      //     },
      //   ]
      // },
      // mingxi: {
      //   dataList: [
      //     { id: '1', username: '评估人1', relations: '直接上级', title1: '题目1', title2: '题目2', title3: '题目3', title4: '题目4' },
      //     { id: '2', username: '评估人2', relations: '相关上级', title1: '题目1', title2: '题目2', title3: '题目3', title4: '题目4' },
      //   ],
      //   columns: [
      //     {
      //       title: '评估人',
      //       dataIndex: 'username',
      //       align: "center",
      //     },
      //     {
      //       title: '评估人与被评估人关系',
      //       dataIndex: 'relations',
      //       align: "center",
      //       width: 180
      //     },
      //     {
      //       title: '题目1',
      //       dataIndex: 'title1',
      //       align: "center",
      //     },
      //     {
      //       title: '题目2',
      //       dataIndex: 'title2',
      //       align: "center",
      //     },
      //     {
      //       title: '题目3',
      //       dataIndex: 'title3',
      //       align: "center",
      //     },
      //     {
      //       title: '题目4',
      //       dataIndex: 'title4',
      //       align: "center",
      //     },
      //   ]
      // },
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: "center",
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          }
        },
        {
          title: '被评估人姓名',
          dataIndex: 'assessedName',
          align: "center",
        },
        {
          title: '被评估人部门',
          dataIndex: 'assessedDept',
          align: "center",
        },
        {
          title: '评估人数',
          dataIndex: 'appraiserUserCount',
          align: "center",
        },
        {
          title: '总分',
          dataIndex: 'scoreTotal',
          align: "center",
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: "center",
          scopedSlots: { customRender: 'action' },
        }
      ],
      columns2: [
        {
          title: '直接上级',
          dataIndex: 'directSuperior',
          align: "center",
          customRender: (text) => text + '%'
        },
        {
          title: '相关上级',
          dataIndex: 'relevantSuperiors',
          align: "center",
          customRender: (text) => text + '%'
        },
        {
          title: '直接平级',
          dataIndex: 'directSibling',
          align: "center",
          customRender: (text) => text + '%'
        },
        {
          title: '相关平级',
          dataIndex: 'relevantSibling',
          align: "center",
          customRender: (text) => text + '%'
        },
        {
          title: '下级',
          dataIndex: 'subordinate',
          align: "center",
          customRender: (text) => text + '%'
        },
      ],
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条"
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      url: {
        list: '/score/scoringAnalyse',
        weightList: '/weight/getInfo'
      }
    }
  },
  watch: {
    $route: {
      handler(to, from) {
        //深度监听，同时也可监听到param参数变化
        this.$nextTick(() => {
          // console.log('to', to)
          // console.log('from', from)
          // if (to.name === 'questionnaire-basic') {
          this.queryParam.questionId = to.query.questionId
          this.loading = true
          Promise.all([
            this.getList(),
            this.getWeightList()
          ]).then(() => {
            this.loading = false
            console.log('this.dataList', this.dataList)
          }).catch(res => {
            this.loading = false
            console.log('res', res)
          })
          // }
        })
      },
      deep: true,
      // 代表在wacth里声明了这个方法之后立即先去执行handler方法
      immediate: true
    }
  },
  methods: {
    getList() {
      return new Promise((resolve, reject) => {
        this.queryParam.page = this.ipagination.current
        this.queryParam.limit = this.ipagination.pageSize
        postAction(this.url.list, this.queryParam).then(res => {
          if (!res.success) {
            return this.$message.error({
              content: res.message,
              onClose: () => reject()
            })
          }
          this.dataList = res.result.list
          this.ipagination.total = res.result.total
          this.weight = res.result.weight
          resolve()
        }).catch(() => {
          reject()
        })
      })
    },
    getWeightList() {
      return new Promise((resolve, reject) => {
        getAction(this.url.weightList, { questionId: this.queryParam.questionId }).then(res => {
          if (!res.success) {
            return this.$message.error({
              content: res.message,
              onClose: () => reject()
            })
          }
          this.weightList = res.result
          resolve()
        }).catch(() => {
          reject()
        })
      })
    },
    searchQuery () {
      this.ipagination.current = 1
      this.getList()
      // 点击查询清空列表选中行
      this.onClearSelected()
    },
    onClearSelected () {
      this.selectedRowKeys = [];
      this.selectionRows = [];
    },
    // 多选
    onSelectChange (selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectionRows = selectionRows;
    },
    searchReset() {
      this.queryParam.assessedName = ''
      this.queryParam.assessedDept = ''
      this.getList()
    },
    reCalculatePage (count) {
      //总数量-count
      let total = this.ipagination.total - count;
      //获取删除后的分页数
      let currentIndex = Math.ceil(total / this.ipagination.pageSize);
      //删除后的分页数<所在当前页
      if (currentIndex < this.ipagination.current) {
        this.ipagination.current = currentIndex;
      }
      console.log('currentIndex', currentIndex)
    },
    tableChangeHandle (pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      //TODO 筛选
      console.log(pagination)
      this.ipagination = pagination;
      this.getList();
    },
    handleExportXls () {
      var params = qs.stringify({
        'X-Access-Token': Vue.ls.get(ACCESS_TOKEN),
        ...this.queryParam
      })
      window.location.href = window._CONFIG['domianURL'] + `/score/exportAnalyse?${ params }`
    },
    handleExportDetailXls() {
      if (this.selectedRowKeys.length !== 1) {
        return this.$message.warn('请选择一位用户导出明细！')
      }
      var params = qs.stringify({
        'X-Access-Token': Vue.ls.get(ACCESS_TOKEN),
        assessedId: this.selectionRows[0].assessedId,
        ...this.queryParam,
      })
      window.location.href = window._CONFIG['domianURL'] + `/score/scoringExport?${ params }`
    },
    handleDetail (id) {
      this.visible = true
    },
    onClose () {
      this.visible = false
    }
  }
}
</script>

<style scoped>

</style>
